import * as React from 'react';
import { Link } from 'react-router';
import { observer } from 'mobx-react';
import { Input, Button, DatePicker, Form, Table, message, Modal } from 'antd';
import { createColumns } from './PageMangerTableColumns';
import { StandardPageListModel } from '../../../model/content/pages/standard/PageListModel';
import { IStandarPageModel } from '../../../model/content/pages/standard/PageModel';
import { PRODUCT_PAGE_URL } from '../../../service/Config';
import { currUser } from "../../../model/CurrUserModel";
import * as moment from 'moment';
import * as QRCode from 'qrcodejs2';

const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
};

@observer
export class PageManager extends React.Component<any, {}> {

    qrcode: any;

    state = {
        store: new StandardPageListModel(),
        columns: createColumns(this),
        previewPage: {} as IStandarPageModel,
        previewVisible: false
    };

    componentDidMount() {
        this.state.store.fetchData().catch(res => message.error("数据加载失败，请重试", 2.5));
    }

    componentWillUnmount() {
        if (this.qrcode) {
            this.qrcode.clear();
            this.qrcode = null;
        }
    }

    private createQRCode(element: HTMLElement) {
        if (!element) {
            this.qrcode && this.qrcode.clear();
            return;
        }
        var url = `${PRODUCT_PAGE_URL}${this.state.previewPage.id}`;

        if (!this.qrcode) {
            this.qrcode = new QRCode(element, {
                text: url,
                width: 128,
                height: 128,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            })
        }
        else {
            this.qrcode.clear();
            this.qrcode.makeCode(url);
        }
    }

    private search = () => {
        var store = this.state.store;
        if (!store.searchTimes) {
            return message.error("请选择搜索时间段", 2.5);
        }
        store.fetchData();
    }

    render() {
        var {store, previewPage, previewVisible} = this.state;
        var {data, meta, loading} = store;
        data = data && data.map(item => ({ ...item, key: item.id }));

        return <div>
            <Form inline>
                <Form.Item>
                    <Input.Search placeholder="名称" value={store.searchName} onChange={e => store.searchName = e.target.value} />
                </Form.Item>
                <Form.Item>
                    <DatePicker.RangePicker
                        showTime
                        format="YYYY-MM-DD HH:mm:ss"
                        defaultValue={store.searchTimes.map(ts => moment(ts))}
                        onChange={value => store.searchTimes = value.map(d => d.unix() * 1000)}
                        ranges={store.searchRanges}
                    />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" size="large" icon="search" onClick={this.search}>搜索</Button>
                </Form.Item>
                {store.searchName != null && <Form.Item>
                    <Button size="large" icon="close-circle-o" onClick={() => {
                        store.searchName = null;
                        store.fetchData();
                    }}>清空</Button>
                </Form.Item>}
            </Form>

            {!currUser.superAdmin && <Link to="/content/page/create">
                <Button type="primary" style={{ margin: "20px 0 0" }}>+新建</Button>
            </Link>}

            <Table
                onChange={this.onTableChange}
                columns={this.state.columns}
                bordered
                loading={loading}
                style={{ marginTop: 20 }}
                dataSource={data as any}
                pagination={{ ...meta, current: meta.current + 1 }} />

            <Modal visible={previewVisible} title="页面信息预览" footer={null} width={780}
                   onCancel={() => this.setState({ previewVisible: false })}>
                {/*<img style={{ width: '100%' }} src={previewImage} />*/}
                <Form horizontal>
                    <Form.Item
                        {...formItemLayout}
                        label="标题">
                        <span>{previewPage.title}</span>
                    </Form.Item>
                    <Form.Item
                        {...formItemLayout}
                        label="链接">
                        <span>{`${PRODUCT_PAGE_URL}${previewPage.id}`}</span>
                    </Form.Item>
                    <Form.Item
                        {...formItemLayout}
                        label="二维码">
                        <div>
                            <div ref={e => this.createQRCode(e)}></div>
                            请使用微信扫描二维码查看
                        </div>
                    </Form.Item>
                </Form>
            </Modal>
        </div>;
    }

    deleteItem(id: string) {
        this.state.store.deleteItem(id).then(res => {
            message.success(`删除成功`, 2.5);
        }, res => {
            message.error(`删除失败，请重试`, 2.5);
        });
    }

    preview(data: IStandarPageModel) {
        this.setState({
            previewVisible: true,
            previewPage: data
        });
    }

    private onTableChange = (pagination) => {
        this.state.store.fetchData(pagination.current - 1, pagination.pageSize);
    }
}